//
//  ASNetworkEngine.m
//
//  Created by dfangjun on 16-2-14.
//  Copyright (c) dfangjun. All rights reserved.
//

#import "ASNetworkEngine.h"
#import "AFNetworking.h"

@interface ASNetworkEngine()

@property (nonatomic,strong,readwrite) NSURL *requestURL;

@end


@implementation ASNetworkEngine


+ (instancetype)sharedInstance
{
    return [[self alloc] initWithBaseURL:nil];
}

- (instancetype)init
{
    return [self initWithBaseURL:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super init];
    
    if (!self)
    {
        return nil;
    }
    
    self.requestURL = url;
    
    //self.requestSerializer = [AFHTTPRequestSerializer serializer];
    //self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    //self.operationQueue = [[NSOperationQueue alloc] init];
    
    return self;
}

- (void)setHeadParameters:(NSDictionary*)headDic sessionMgr:(AFHTTPSessionManager*)sessionMgr
{
    if (headDic && headDic.count > 0)
    {
        for(NSString* key in headDic.allKeys)
        {
            NSString* value = [headDic objectForKey:key];
            [sessionMgr.requestSerializer setValue:key forHTTPHeaderField:value];
        }
    }
}

//- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer
//{
//    NSParameterAssert(requestSerializer);
//    
//    _requestSerializer = requestSerializer;
//}
//
//- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer
// {
//    NSParameterAssert(responseSerializer);
//    
//    _responseSerializer = responseSerializer;
//}

//- (void)HTTPRequestOperationWithRequest:(NSURLRequest *)request
//                                                    success:(void (^)( id responseObject))success
//                                                    failure:(void (^)( NSError *error))failure
//{
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    operation.responseSerializer = self.responseSerializer;
//    operation.shouldUseCredentialStorage = YES;
//    [operation setCompletionBlockWithSuccess:success failure:failure];
//    self.tempOperation = operation;
//    return operation;
//}

#pragma mark - POST

- (void)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self POST:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)POST:(NSString *)URLString
                  headParameters:(id)headParameters
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self POST:URLString headParameters:headParameters bodyParameters:parameters isBodyEncoding:NO success:success failure:failure];
}

- (void)POST:(NSString *)URLString
                  headParameters:(id)headParameters
                      bodyParameters:(id)bodyParameters
                    isBodyEncoding:(BOOL)isBodyEncoding
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString];
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }

    [sessionManager POST:[url absoluteString] parameters:bodyParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
}

#pragma mark - PUT

- (void)PUT:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self PUT:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)PUT:(NSString *)URLString
                  headParameters:(id)headParameters
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self PUT:URLString headParameters:headParameters bodyParameters:parameters isBodyEncoding:NO success:success failure:failure];
}

- (void)PUT:(NSString *)URLString
                  headParameters:(id)headParameters
                  bodyParameters:(id)bodyParameters
                  isBodyEncoding:(BOOL)isBodyEncoding
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString];
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }
    
    [sessionManager PUT:[url absoluteString] parameters:bodyParameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

#pragma mark - GET

- (void)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    
    [self GET:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)GET:(NSString *)URLString
                 headParameters:(NSDictionary*)headParameters
                     parameters:(id)parameters
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    [self GET:URLString headParameters:headParameters parameters:parameters DownloadProgress:nil success:success failure:failure];
}

- (void)GET:(NSString *)URLString
                 headParameters:(NSDictionary*)headParameters
                     parameters:(id)parameters
               DownloadProgress:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downLoadProgress
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    NSString *urlStr = [NSString stringWithFormat:@"%@", URLString];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    //NSURL *url= [NSURL URLWithString:URLString] ;
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }
    
    //sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    
//    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    [sessionManager GET:[url absoluteString] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        if (downLoadProgress)
        {
            downLoadProgress((NSUInteger)downloadProgress.completedUnitCount, downloadProgress.totalUnitCount, 0);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

- (void)GETImage:(NSString *)URLString
                          parameters:(id)parameters
                             success:(void (^)( id responseObject))success
                             failure:(void (^)( NSError *error))failure
{
    [self GETImage:URLString parameters:parameters DownloadProgress:nil success:success failure:failure];
}

- (void)GETImage:(NSString *)URLString
                          parameters:(id)parameters
                    DownloadProgress:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downLoadProgress
                             success:(void (^)( id responseObject))success
                             failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString];
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
    
    //sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [sessionManager GET:[url absoluteString] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        if (downLoadProgress)
        {
            downLoadProgress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount, 0);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

/**
 *  @brief  下载文件
 *
 *  @param url             被下载的文件url
 *  @param savePath        将下载的文件保存到本地的全路径，包括文件名
 *  @param progressBlock   下载进度回调
 *  @param completionBlock 下载完成回调
 *  @param failure         失败回调
 */
- (void)downloadWithUrl:(NSString *)url
               savePath:(NSString *)savePath
          progressBlock:(void (^)(long long bytesRead, long long totalBytes))progressBlock
        completionBlock:(void (^)(id responseObject))completionBlock
                failure:(void (^)(NSString* errorMsg))failure
{
    NSURL *nsUrl= [NSURL URLWithString:url] ;
    if (nsUrl == NULL)
    {
        return;
    }

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager GET:[nsUrl absoluteString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        if (progressBlock)
        {
            progressBlock(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 主线程中执行
        NSData* data = (NSData *)responseObject;
        [data writeToFile:savePath atomically:YES];
        
        completionBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error.description);
    }];
}

/**
 *  @brief  上传图片
 *
 *  @param url               服务器url
 *  @param image             图片
 *  @param progressBlock     过程回调
 *  @param completionBlock   成功回调
 *  @param failure           失败回调
 */

- (void)uploadImageWithUril:(NSString *)url
                      image:(UIImage *)image
              progressBlock:(void (^)(long long bytesRead, long long totalBytes))progressBlock
            completionBlock:(void (^)(id responseObject))completionBlock
                    failure:(void (^)(NSString* errorMsg))failure
{
    NSURL *nsUrl= [NSURL URLWithString:url];
    if (nsUrl == NULL)
    {
        return;
    }
    
    //image name
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString* tmp = [formatter stringFromDate:[NSDate date]];
    NSString* fileName = [[NSString alloc] initWithFormat:@"%@.png", tmp];

    if (SYSTEM_VERSION >= 8.0)
    {
        // iOS 8 later
        AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
        sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                    @"text/json",
                                                                    @"text/javascript",
                                                                    @"text/html",
                                                                    @"text/plain",
                                                                    nil];
        
        [sessionManager POST:[[nsUrl absoluteString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                  parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData* imageData = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            if (progressBlock)
            {
                progressBlock(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSLog(@"file upload succ");
            completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error.description);
        }];
    }
    else
    {
        // 此处需要判断是否没有上传图片
        if (image == nil)
        {
            AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
            sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
            sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                        @"text/json",
                                                                        @"text/javascript",
                                                                        @"text/html",
                                                                        @"text/plain",
                                                                        nil];
            [sessionManager POST:[[nsUrl absoluteString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                      parameters:nil
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                             
                             completionBlock(responseObject);
                         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                             
                             failure(error.description);
                         }];
            
            return;
        }
        
        // iOS 7
        NSString *tmpFileName = [NSString stringWithFormat:@"%f", [NSDate timeIntervalSinceReferenceDate]];
        NSURL* tmlFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:tmpFileName]];
        NSMutableURLRequest *multipartRequest = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[nsUrl absoluteString] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData* imageData = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } error:nil];
        
        [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:multipartRequest writingStreamContentsToFile:tmlFileUrl completionHandler:^(NSError * _Nullable error) {
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:multipartRequest fromFile:tmlFileUrl progress:^(NSProgress * _Nonnull uploadProgress) {
                
                if (progressBlock)
                {
                    progressBlock(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
                }
            } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                
                [[NSFileManager defaultManager] removeItemAtURL:tmlFileUrl error:nil];
                if (error)
                {
                    if (failure)
                    {
                        failure(error.description);
                    }
                }
                else
                {
                    if (completionBlock)
                    {
                        completionBlock(responseObject);
                    }
                }
            }];
            
            [uploadTask resume];
        }];
    }
}

/**
 *  @brief  上传多张图片
 *
 *  @param url               服务器url
 *  @param array             图片
 *  @param progressBlock     过程回调
 *  @param completionBlock   成功回调
 *  @param failure           失败回调
 */

- (void)uploadImagesWithUrl:(NSString *)url
                      image:(NSMutableArray *)imageArray
              progressBlock:(void (^)(long long bytesRead, long long totalBytes))progressBlock
            completionBlock:(void (^)(id responseObject))completionBlock
                    failure:(void (^)(NSString* errorMsg))failure
{
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *nsUrl= [NSURL URLWithString:url];
    if (nsUrl == NULL)
    {
        return;
    }

    if (SYSTEM_VERSION >= 8.0)
    {
        // iOS 8 later
        AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
        sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                    @"text/json",
                                                                    @"text/javascript",
                                                                    @"text/html",
                                                                    @"text/plain",
                                                                    nil];
        
        [sessionManager POST:[[nsUrl absoluteString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            for (NSInteger i = 0; i < [imageArray count]; i++)
            {
                NSData* imageData = [imageArray objectAtIndex:i];
                //NSData* imageData = UIImagePNGRepresentation(image);
                NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString* tmp = [formatter stringFromDate:[NSDate date]];
                NSString* sCount = [NSString stringWithFormat:@"%ld",(long)i];
                NSString* fileName = [[NSString alloc] initWithFormat:@"%@%@.png", tmp,sCount];
                
                [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            if (progressBlock)
            {
                progressBlock(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSLog(@"file upload succ");
            completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error.description);
        }];
    }
    else
    {
        // 此处需要增加判断 如果没有上传图片的情况
        if ([imageArray count] == 0)
        {
            AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
            sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
            sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                        @"text/json",
                                                                        @"text/javascript",
                                                                        @"text/html",
                                                                        @"text/plain",
                                                                        nil];
            [sessionManager POST:[[nsUrl absoluteString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                      parameters:nil
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                             completionBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                failure(error.description);
            }];
            
            return;
        }
        
        // iOS 7
        NSString *tmpFileName = [NSString stringWithFormat:@"%f", [NSDate timeIntervalSinceReferenceDate]];
        NSURL* tmlFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:tmpFileName]];
        NSMutableURLRequest *multipartRequest = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[[nsUrl absoluteString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            for (NSInteger i = 0; i < [imageArray count]; i++)
            {
                NSData* imageData = [imageArray objectAtIndex:i];
                //NSData* imageData = UIImagePNGRepresentation(image);
                NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString* tmp = [formatter stringFromDate:[NSDate date]];
                NSString* fileName = [[NSString alloc] initWithFormat:@"%@.png", tmp];
                
                [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
            }
            
        } error:nil];
        
        [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:multipartRequest writingStreamContentsToFile:tmlFileUrl completionHandler:^(NSError * _Nullable error) {
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:multipartRequest fromFile:tmlFileUrl progress:^(NSProgress * _Nonnull uploadProgress) {
                
                if (progressBlock)
                {
                    progressBlock(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
                }
            } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                
                [[NSFileManager defaultManager] removeItemAtURL:tmlFileUrl error:nil];
                if (error)
                {
                    if (failure)
                    {
                        failure(error.description);
                    }
                }
                else
                {
                    if (completionBlock)
                    {
                        completionBlock(responseObject);
                    }
                }
            }];
            
            [uploadTask resume];
        }];
    }
}

/**
 *  @brief  上传视频
 *
 *  @param url               服务器url
 *  @param image             视频
 *  @param progressBlock     过程回调
 *  @param completionBlock   成功回调
 *  @param failure           失败回调
 */
- (void)uploadVideoWithUril:(NSString *)url
                      video:(NSData *)videoData
              progressBlock:(void (^)(long long bytesRead, long long totalBytes))progressBlock
            completionBlock:(void (^)(id responseObject))completionBlock
                    failure:(void (^)(NSString* errorMsg))failure
{
    NSURL *nsUrl= [NSURL URLWithString:url];
    if (nsUrl == NULL)
    {
        return;
    }
    
    //video name
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString* tmp = [formatter stringFromDate:[NSDate date]];
    NSString* fileName = [[NSString alloc] initWithFormat:@"%@.mov", tmp];
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    [sessionManager POST:[nsUrl absoluteString] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:videoData name:@"userfile" fileName:fileName mimeType:@"video/mov"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progressBlock)
        {
            progressBlock(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"file upload succ");
        completionBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error.description);
    }];
}


#pragma mark - NSObject
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p, requestURL: %@, operationQueue: %@>",
            NSStringFromClass([self class]),
            self,
            self.requestURL,
            self.operationQueue];
}


- (void)cancelAllHTTPOperationsWithMethod
{
    [self.operationQueue cancelAllOperations];
}

- (void)downLoadData:(NSString*)path image:(UIImageView*)imageView
{
    __block NSData* responeData = nil;
    __block NSString* downPath = path;
    __block UIImageView* downImageview = imageView;
    //__weak UIImageView *downImageview = imageView;
    @autoreleasepool
    {
        dispatch_queue_t newQueue  = [self getDownImageQueue];
        
        dispatch_async(newQueue, ^{
            
            NSURL *url = [NSURL URLWithString:downPath];
            
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
                                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                      timeoutInterval:60.0f];
            NSError *error = [[NSError alloc] init];
            NSURLResponse *response = [[NSURLResponse alloc] init];
            
            responeData = [NSURLConnection sendSynchronousRequest:request
                                                returningResponse:&response
                                                            error:&error];

            dispatch_sync(dispatch_get_main_queue(), ^(){
                // 这里的代码会在主线程执行
                downImageview.image = [UIImage imageWithData: responeData];
                
            });
            
            
        });
        
    };
    
}

/**
 *  获取发送消息队列，创建子线程
 *
 *  @return
 */
- (id)getDownImageQueue
{
    static dispatch_once_t onceTokenQueue;
    dispatch_once(&onceTokenQueue, ^{
        
        downImageQueue = dispatch_queue_create("attendenceSys.downImage", DISPATCH_QUEUE_SERIAL);
        
    });
    
    return downImageQueue;
}

@end







